<template>
  <el-dialog
    v-model="dialogVisible"
    title="降雨数据统计图表"
    width="1200px"
    :close-on-click-modal="false"
  >
    <!-- 控制面板 -->
    <el-card class="control-panel" shadow="never">
      <el-form :model="chartForm" :inline="true" label-width="80px">
        <el-form-item label="监测站点">
          <el-select
            v-model="chartForm.stationId"
            placeholder="请选择监测站点"
            clearable
            style="width: 200px"
            @change="updateChart"
          >
            <el-option label="全部站点" value="" />
            <el-option
              v-for="station in rainfallStations"
              :key="station.id"
              :label="station.name"
              :value="station.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图表类型">
          <el-select
            v-model="chartForm.chartType"
            placeholder="请选择图表类型"
            style="width: 200px"
            @change="updateChart"
          >
            <el-option label="降雨量趋势" value="rainfall" />
            <el-option label="降雨强度" value="intensity" />
            <el-option label="降雨类型分布" value="type" />
            <el-option label="典型降雨统计" value="typical" />
            <el-option label="月度统计" value="monthly" />
            <el-option label="综合分析" value="comprehensive" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="chartForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
            @change="updateChart"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateChart">
            <el-icon><Refresh /></el-icon>
            刷新图表
          </el-button>
          <el-button type="success" @click="exportChart">
            <el-icon><Download /></el-icon>
            导出图表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图表区域 -->
    <el-card class="chart-container" shadow="never">
      <div ref="chartRef" class="chart" v-loading="chartLoading"></div>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="statistics-panel" shadow="never">
      <template #header>
        <span class="panel-title">统计信息</span>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">总降雨量</div>
            <div class="stat-value">{{ statistics.totalRainfall }} mm</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">平均降雨量</div>
            <div class="stat-value">{{ statistics.avgRainfall }} mm</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">最大降雨量</div>
            <div class="stat-value">{{ statistics.maxRainfall }} mm</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">降雨天数</div>
            <div class="stat-value">{{ statistics.rainyDays }} 天</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">典型降雨</div>
            <div class="stat-value">{{ statistics.typicalCount }} 次</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">暴雨天数</div>
            <div class="stat-value">{{ statistics.heavyRainDays }} 天</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">最大强度</div>
            <div class="stat-value">{{ statistics.maxIntensity }} mm/h</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-label">平均强度</div>
            <div class="stat-value">{{ statistics.avgIntensity }} mm/h</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="data-table" shadow="never">
      <template #header>
        <span class="panel-title">详细数据</span>
      </template>
      <el-table :data="filteredData" stripe border max-height="300">
        <el-table-column prop="stationName" label="监测站点" width="120" />
        <el-table-column prop="rainfallDate" label="降雨日期" width="120" />
        <el-table-column prop="totalRainfall" label="降雨量(mm)" width="100" />
        <el-table-column prop="maxIntensity" label="最大强度(mm/h)" width="120" />
        <el-table-column prop="duration" label="持续时长(h)" width="100" />
        <el-table-column prop="rainfallType" label="降雨类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getRainfallTagType(row.rainfallType)">
              {{ row.rainfallType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTypical" label="是否典型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isTypical ? 'success' : 'info'">
              {{ row.isTypical ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="weatherCondition" label="天气状况" />
      </el-table>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

interface Props {
  visible: boolean
  chartData?: any[]
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  chartData: () => []
})

const emit = defineEmits<Emits>()

// 监测站点
const rainfallStations = ref([
  { id: 1, name: '西音水库主站' },
  { id: 2, name: '大坝监测站' },
  { id: 3, name: '库区中心站' },
  { id: 4, name: '入库口站' },
  { id: 5, name: '出库口站' },
  { id: 6, name: '上游监测站' },
  { id: 7, name: '下游监测站' }
])

const chartRef = ref<HTMLDivElement>()
const chartInstance = ref<echarts.ECharts>()
const chartLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 图表表单
const chartForm = reactive({
  stationId: '',
  chartType: 'rainfall',
  dateRange: []
})

// 统计信息
const statistics = reactive({
  totalRainfall: 0,
  avgRainfall: 0,
  maxRainfall: 0,
  rainyDays: 0,
  typicalCount: 0,
  heavyRainDays: 0,
  maxIntensity: 0,
  avgIntensity: 0
})

// 过滤后的数据
const filteredData = computed(() => {
  let data = props.chartData || []
  
  if (chartForm.stationId) {
    data = data.filter(item => item.stationId === chartForm.stationId)
  }
  
  if (chartForm.dateRange && chartForm.dateRange.length === 2) {
    const [startDate, endDate] = chartForm.dateRange
    data = data.filter(item => {
      return item.rainfallDate >= startDate && item.rainfallDate <= endDate
    })
  }
  
  return data
})

// 获取降雨类型标签样式
const getRainfallTagType = (type: string) => {
  const typeMap = {
    '小雨': 'success',
    '中雨': 'primary',
    '大雨': 'warning',
    '暴雨': 'danger',
    '大暴雨': 'danger',
    '特大暴雨': 'danger'
  }
  return typeMap[type] || ''
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance.value = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value) return
  
  chartLoading.value = true
  
  setTimeout(() => {
    const option = getChartOption()
    chartInstance.value?.setOption(option, true)
    updateStatistics()
    chartLoading.value = false
  }, 500)
}

// 获取图表配置
const getChartOption = () => {
  const data = filteredData.value
  
  switch (chartForm.chartType) {
    case 'rainfall':
      return getRainfallTrendOption(data)
    case 'intensity':
      return getIntensityOption(data)
    case 'type':
      return getTypeDistributionOption(data)
    case 'typical':
      return getTypicalStatisticsOption(data)
    case 'monthly':
      return getMonthlyStatisticsOption(data)
    case 'comprehensive':
      return getComprehensiveOption(data)
    default:
      return getRainfallTrendOption(data)
  }
}

// 降雨量趋势图
const getRainfallTrendOption = (data: any[]) => {
  const dates = data.map(item => item.rainfallDate)
  const rainfalls = data.map(item => item.totalRainfall)
  
  return {
    title: {
      text: '降雨量趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0]
        return `${param.axisValue}<br/>降雨量: ${param.value} mm`
      }
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '降雨量(mm)'
    },
    series: [{
      name: '降雨量',
      type: 'line',
      data: rainfalls,
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      itemStyle: {
        color: '#409eff'
      }
    }]
  }
}

// 降雨强度图
const getIntensityOption = (data: any[]) => {
  const dates = data.map(item => item.rainfallDate)
  const intensities = data.map(item => item.maxIntensity)
  
  return {
    title: {
      text: '降雨强度分布图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '强度(mm/h)'
    },
    series: [{
      name: '最大强度',
      type: 'bar',
      data: intensities,
      itemStyle: {
        color: '#67c23a'
      }
    }]
  }
}

// 降雨类型分布图
const getTypeDistributionOption = (data: any[]) => {
  const typeCount = {}
  data.forEach(item => {
    typeCount[item.rainfallType] = (typeCount[item.rainfallType] || 0) + 1
  })
  
  const pieData = Object.entries(typeCount).map(([name, value]) => ({ name, value }))
  
  return {
    title: {
      text: '降雨类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      name: '降雨类型',
      type: 'pie',
      radius: '50%',
      data: pieData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
}

// 典型降雨统计图
const getTypicalStatisticsOption = (data: any[]) => {
  const typicalData = data.filter(item => item.isTypical)
  const normalData = data.filter(item => !item.isTypical)
  
  return {
    title: {
      text: '典型降雨统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      data: ['典型降雨', '普通降雨'],
      bottom: 0
    },
    series: [{
      name: '降雨统计',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [
        { value: typicalData.length, name: '典型降雨' },
        { value: normalData.length, name: '普通降雨' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
}

// 月度统计图
const getMonthlyStatisticsOption = (data: any[]) => {
  const monthlyData = {}
  data.forEach(item => {
    const month = item.rainfallDate.substring(0, 7)
    if (!monthlyData[month]) {
      monthlyData[month] = { count: 0, totalRainfall: 0 }
    }
    monthlyData[month].count++
    monthlyData[month].totalRainfall += item.totalRainfall
  })
  
  const months = Object.keys(monthlyData).sort()
  const counts = months.map(month => monthlyData[month].count)
  const totals = months.map(month => monthlyData[month].totalRainfall)
  
  return {
    title: {
      text: '月度降雨统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['降雨次数', '总降雨量']
    },
    xAxis: {
      type: 'category',
      data: months
    },
    yAxis: [
      {
        type: 'value',
        name: '次数',
        position: 'left'
      },
      {
        type: 'value',
        name: '降雨量(mm)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '降雨次数',
        type: 'bar',
        data: counts,
        itemStyle: {
          color: '#409eff'
        }
      },
      {
        name: '总降雨量',
        type: 'line',
        yAxisIndex: 1,
        data: totals,
        itemStyle: {
          color: '#67c23a'
        }
      }
    ]
  }
}

// 综合分析图
const getComprehensiveOption = (data: any[]) => {
  const dates = data.map(item => item.rainfallDate)
  const rainfalls = data.map(item => item.totalRainfall)
  const intensities = data.map(item => item.maxIntensity)
  const durations = data.map(item => item.duration)
  
  return {
    title: {
      text: '综合分析图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['降雨量', '最大强度', '持续时长']
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '降雨量(mm)',
        position: 'left'
      },
      {
        type: 'value',
        name: '强度(mm/h) / 时长(h)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '降雨量',
        type: 'bar',
        data: rainfalls,
        itemStyle: {
          color: '#409eff'
        }
      },
      {
        name: '最大强度',
        type: 'line',
        yAxisIndex: 1,
        data: intensities,
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '持续时长',
        type: 'line',
        yAxisIndex: 1,
        data: durations,
        itemStyle: {
          color: '#e6a23c'
        }
      }
    ]
  }
}

// 更新统计信息
const updateStatistics = () => {
  const data = filteredData.value
  
  if (data.length === 0) {
    Object.assign(statistics, {
      totalRainfall: 0,
      avgRainfall: 0,
      maxRainfall: 0,
      rainyDays: 0,
      typicalCount: 0,
      heavyRainDays: 0,
      maxIntensity: 0,
      avgIntensity: 0
    })
    return
  }
  
  const totalRainfall = data.reduce((sum, item) => sum + item.totalRainfall, 0)
  const maxRainfall = Math.max(...data.map(item => item.totalRainfall))
  const typicalCount = data.filter(item => item.isTypical).length
  const heavyRainDays = data.filter(item => item.totalRainfall >= 50).length
  const maxIntensity = Math.max(...data.map(item => item.maxIntensity))
  const avgIntensity = data.reduce((sum, item) => sum + item.maxIntensity, 0) / data.length
  
  Object.assign(statistics, {
    totalRainfall: totalRainfall.toFixed(1),
    avgRainfall: (totalRainfall / data.length).toFixed(1),
    maxRainfall: maxRainfall.toFixed(1),
    rainyDays: data.length,
    typicalCount,
    heavyRainDays,
    maxIntensity: maxIntensity.toFixed(1),
    avgIntensity: avgIntensity.toFixed(1)
  })
}

// 导出图表
const exportChart = () => {
  if (!chartInstance.value) return
  
  const url = chartInstance.value.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff'
  })
  
  const link = document.createElement('a')
  link.download = `降雨统计图表_${new Date().toISOString().slice(0, 10)}.png`
  link.href = url
  link.click()
  
  ElMessage.success('图表导出成功')
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

// 监听弹窗显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    nextTick(() => {
      initChart()
    })
  }
})

// 监听数据变化
watch(() => props.chartData, () => {
  if (dialogVisible.value) {
    updateChart()
  }
}, { deep: true })

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
})
</script>

<style scoped>
.control-panel {
  margin-bottom: 20px;
}

.chart-container {
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 400px;
}

.statistics-panel {
  margin-bottom: 20px;
}

.panel-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.stat-item {
  text-align: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  background: #fafafa;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.data-table {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>